package org.grottarossa.ui.core.controls.document.upload;

import java.util.ArrayList;

import org.grottarossa.template.data.pojo.content.Content;
import org.grottarossa.template.data.pojo.content.DocumentList;
import org.grottarossa.ui.core.ApplicationSession;


/***
 * Gestisce la logica del controllo di caricamento file sul back-end
 * @author 
 *
 */
public class UploadDocumentPresenter implements IDocumentUploaderObserver
{
	/*** View ***/
	private final UploadDocument m_view;

	/*** Content di riferimento ***/
	private Content m_content;

	/*** Osservatori ***/
	private ArrayList<IDocumentUploaderObserver> m_observers = new ArrayList<IDocumentUploaderObserver>();

	private final ApplicationSession m_appSession;

	public UploadDocumentPresenter(ApplicationSession appSession, UploadDocument view, Content content)
	{
		this.m_appSession = appSession;
		this.m_view = view;
		m_content = content;
		m_view.setPresenter(this);
	}

	public void initialize()
	{
		m_view.initialize(m_content.getDocumentID());
	}

	/***
	 * Notifica agli osservatori la buona riuscita dell'upload
	 */
	public void documentUploaded(String filename)
	{
		try
		{
			DocumentList versions = m_appSession.getBuilder().getDocumentManagement().getDocumentVersions(m_content.getDocumentID());
			m_content.setDocumentList(versions);

			for(IDocumentUploaderObserver o : m_observers)
			{
				o.documentUploaded(filename);
			}
		}
		catch(Exception ex)
		{
			m_view.showError(ex);
		}
	}

	/***
	 * Aggiunge un osservatore
	 * @param observer
	 */
	public void addObserver(IDocumentUploaderObserver observer)
	{
		m_observers .add(observer);
	}
}
